package cn.stylefeng.guns.modular.tool.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.justGoodsInfoApi;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.order.entity.OrderPutExcelItem;
import cn.stylefeng.guns.modular.order.model.params.OrderPutParam;
import cn.stylefeng.guns.modular.order.model.result.OrderPutResult;
import cn.stylefeng.guns.modular.tool.entity.ToolOrderPut;
import cn.stylefeng.guns.modular.tool.mapper.ToolOrderPutMapper;
import cn.stylefeng.guns.modular.tool.model.params.ToolOrderPutDetailedParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolOrderPutParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolOrderPutResult;
import cn.stylefeng.guns.modular.tool.service.ToolOrderPutDetailedService;
import cn.stylefeng.guns.modular.tool.service.ToolOrderPutService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 云仓入库表 服务实现类
 * </p>
 * @author zhucx
 * @since 2023-04-03
 */
@Service
public class ToolOrderPutServiceImpl extends ServiceImpl<ToolOrderPutMapper, ToolOrderPut> implements ToolOrderPutService {



    @Override
    public void add(ToolOrderPutParam param){
        ToolOrderPut entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(ToolOrderPutParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(ToolOrderPutParam param){
        ToolOrderPut oldEntity = getOldEntity(param);
        ToolOrderPut newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public ToolOrderPutResult findBySpec(ToolOrderPutParam param,Long operateId){
        return this.baseMapper.findBySpec(param,operateId);
    }



	@Override
	public OrderPutResult findBySpecNew(OrderPutParam param, Long operateId) {
		return this.baseMapper.findBySpecNew(param,operateId);
	}

	@Override
    public List<ToolOrderPutResult> findListBySpec(ToolOrderPutParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(ToolOrderPutParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(ToolOrderPutParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private ToolOrderPut getOldEntity(ToolOrderPutParam param) {
        return this.getById(getKey(param));
    }

    private ToolOrderPut getEntity(ToolOrderPutParam param) {
        ToolOrderPut entity = new ToolOrderPut();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

	@Override
	public boolean checkCustomerOrder(String putCustomerNumber) {
		return this.baseMapper.checkCustomerOrder(putCustomerNumber)==null?false:true;
	}

	@Override
	public ToolOrderPut findByThelastone() {
		return this.baseMapper.findByThelastone();
	}
	
	private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(Double.toString(cell.getNumericCellValue())).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }
	
    @Resource
    private BasicCustomerService basicCustomerService;

    @Resource
    private BasicWarehouseService basicWarehouseService;

    @Resource
    private BasicGoodsService basicGoodsService;

    @Resource
    private UserService userService;
	
	/**
	 * 处理入库订单导入
	 */
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData getExceldata(MultipartFile file,ToolOrderPutParam toolOrderPutParam, ResponseData data) throws IOException {
		String fileName = file.getOriginalFilename();
		List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("上传文件格式不正确");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            OrderPutExcelItem excelItem = new OrderPutExcelItem();

            String  carNumber = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(carNumber)) {
                excelItem.setCarNumber(carNumber);//车牌号
			}

            String goodsNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(1));
            if (ToolUtil.isNotEmpty(goodsNumber)) {
                excelItem.setGoodsNumber(goodsNumber);//商品编号
			}

            String goodsName = getCellValue(row.getCell(2));
            if (ToolUtil.isNotEmpty(goodsName)) {
                excelItem.setGoodsName(goodsName);//商品名称
			}

            String batchnumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(3));
            if (ToolUtil.isNotEmpty(batchnumber)) {
                excelItem.setBatchnumber(batchnumber);//生产日期
			}

            String putnum = getCellValue(row.getCell(4));
            if (ToolUtil.isNotEmpty(putnum)) {
            	BigDecimal as = new BigDecimal(0);
            	BigDecimal putnumb = new BigDecimal(putnum);
            	if(putnumb.compareTo(as) != 1) {
            		continue;
            	}
                excelItem.setPutnum(putnum);//应入数量
			}

            String detailedMoney = getCellValue(row.getCell(5));
            if (ToolUtil.isNotEmpty(detailedMoney)) {
                excelItem.setDetailedMoney(detailedMoney);//金额
			}

            String putvolume = getCellValue(row.getCell(6));
            if (ToolUtil.isNotEmpty(putvolume)) {
                excelItem.setPutvolume(putvolume);//应入体积
			}

            String shipmentnumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(7));
            if (ToolUtil.isNotEmpty(shipmentnumber)) {
                excelItem.setShipmentnumber(shipmentnumber);//客户货运订单号   (客户单号){
			}

            String putCustomerNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(8));
            if (ToolUtil.isNotEmpty(putCustomerNumber)) {
                excelItem.setPutCustomerNumber(putCustomerNumber);//客户交货单号
			}

            String goodsType = getCellValue(row.getCell(9));
            if (ToolUtil.isNotEmpty(goodsType)) {
                excelItem.setGoodsType(goodsType);//品类描述
			}

            String goodsUnit = getCellValue(row.getCell(10));
            if (ToolUtil.isNotEmpty(goodsUnit)) {
                excelItem.setGoodsUnit(goodsUnit);//基本单位
			}

            String recommend = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(11));
            if (ToolUtil.isNotEmpty(recommend)) {
                excelItem.setRecommend(recommend);//推荐批次
			}

            String notes = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(12));
            if (ToolUtil.isNotEmpty(notes)) {
                excelItem.setNotes(notes);
			}

            String goodsbatchs = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(13));
            if (ToolUtil.isNotEmpty(goodsbatchs)) {
                excelItem.setGoodsbatchs(goodsbatchs);
			}
            
            list.add(excelItem);
        }

		if(toolOrderPutParam.getWarehouseId()==null||toolOrderPutParam.getPutCustomerId()==null) {
			data.setSuccess(false);
			data.setMessage("请填写订单基本信息!");
			return data;
		}
		List<ToolOrderPutParam> orderPutList = new ArrayList<ToolOrderPutParam>();//批量保存的 入库订单list
		List<ToolOrderPutDetailedParam> detailedList = new ArrayList<ToolOrderPutDetailedParam>();//批量保存的 订单商品明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(toolOrderPutParam.getPutCustomerId());//客户信息
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(toolOrderPutParam.getWarehouseId());//仓库信息
		//查询最新 入库订单
		ToolOrderPut toolOrderPut = this.findByThelastone();
    	int putNumber = 1;
    	if (toolOrderPut!=null) {
    		putNumber = toolOrderPut.getId()+1;
		} 
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
		String trayCode = getOperateIdOrderPrefix(user);
		for (OrderPutExcelItem excelItem : list) {
			if (ToolUtil.isEmpty(excelItem.getGoodsNumber())&&ToolUtil.isEmpty(excelItem.getGoodsName())) {
				break;
			} 
			if(ToolUtil.isEmpty(excelItem.getGoodsNumber())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中商品编号不得为空!");
				return data;
			}
			if(ToolUtil.isEmpty(excelItem.getPutnum())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中应入数量不得为空!");
				return data;
			}
			//通过 导入的客户单号 查询是否存在
			ToolOrderPutParam opp = new ToolOrderPutParam();
			boolean whether2 = false;
			if(ToolUtil.isEmpty(excelItem.getShipmentnumber())) {
				whether2 = true;
				excelItem.setShipmentnumber(trayCode+"-"+"YCRK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+(putNumber));
			}
			opp.setPutCustomerNumber(excelItem.getShipmentnumber());//客户单号 (客户货运订单号)
			ToolOrderPutResult toolOrderPutResult = this.findBySpec(opp,null);//状态不等于 作废
			//如果不存在
			if(toolOrderPutResult==null) {
				//新增入库订单
				opp.setPutNumber(trayCode+"-"+"YCRK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+(putNumber));
		    	opp.setPutCustomerId(toolOrderPutParam.getPutCustomerId());//客户id
		    	opp.setPutCustomerName(basicCustomer.getCustomerName());//客户名称
		    	opp.setWarehouseId(toolOrderPutParam.getWarehouseId());//仓库id
		    	opp.setWarehouseName(basicWarehouse.getWarehouseName());//仓库名称
		    	opp.setPutType("PICKUP_STORAGE");//入库类别 默认为‘提货入库’
	opp.setPutMode("WINDOW_RECEIVING");//入库方式 默认为‘窗口接货’  不生成货运订单
		    	opp.setSettlement(toolOrderPutParam.getSettlement());//结算方式
		    	opp.setCarnumber(excelItem.getCarNumber());//车牌号
		    	opp.setBillstate("PENDING_SUBMIT");//订单状态
		    	opp.setCreateName(user.getName());//制单人名称
		    	opp.setCreateTime(new Date());
		    	opp.setNotes(excelItem.getNotes());
		    	opp.setDeliverId(deliverId);//交付id
		    	opp.setDeptId(deptId);//部门id
		    	boolean whether = false;//判断客户单号  是否重复
		    	for (ToolOrderPutParam opp2 : orderPutList) {
					if (opp2.getPutCustomerNumber().equals(opp.getPutCustomerNumber())) {
						whether = true;
						toolOrderPutResult = new ToolOrderPutResult();
		    			ToolUtil.copyProperties(opp2,toolOrderPutResult);
					}
				}
		    	if (!whether) {
		    		orderPutList.add(opp);
		    		if(!whether2) {
		    			putNumber++;
		    		}
		    		toolOrderPutResult = new ToolOrderPutResult();
	    			ToolUtil.copyProperties(opp,toolOrderPutResult);
				}
    			opp = new ToolOrderPutParam();
			} else {
				//如果 导入的客户单号 已存在
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中客户单号:"+excelItem.getShipmentnumber()+"已存在!");
				return data;
			}
			
			//通过商品编号 查询商品是否存在
			BasicGoodsParam bgpParam = new BasicGoodsParam();
			bgpParam.setGoodsNumber(excelItem.getGoodsNumber());
			bgpParam.setGoodsCustomerId(Integer.parseInt(toolOrderPutParam.getPutCustomerId().toString()));
			BasicGoodsResult bgrBasicGoodsResult = basicGoodsService.findBySpec(bgpParam,null);
			//计算 单价，体积单位
			BigDecimal putnum = new BigDecimal(excelItem.getPutnum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);//应入数量
			BigDecimal putvolume =  new BigDecimal(0);//应入体积
			BigDecimal v = new BigDecimal(0);//体积单位
			BigDecimal u = new BigDecimal(0);//单价
			if (ToolUtil.isNotEmpty(excelItem.getPutvolume())) {
				putvolume =  new BigDecimal(excelItem.getPutvolume()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				v = putvolume.divide(putnum,8,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
			} else {
				if (bgrBasicGoodsResult != null && ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsVolume())) {
					v = new BigDecimal(bgrBasicGoodsResult.getGoodsVolume()).setScale(8, BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
					putvolume =  putnum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				} else {
					v =  new BigDecimal("0.1");
				}
			}
			BigDecimal detailedMoney = new BigDecimal(0);//金额
			if (ToolUtil.isNotEmpty(excelItem.getDetailedMoney())) {
				detailedMoney = new BigDecimal(excelItem.getDetailedMoney()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				u = detailedMoney.divide(putnum,3,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留3位)
			} else {
				if (bgrBasicGoodsResult != null && ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsCharging())) {
					u = new BigDecimal(bgrBasicGoodsResult.getGoodsCharging()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					detailedMoney = putnum.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				} else {
					u = new BigDecimal("10");
				}
			}
			BigDecimal as = new BigDecimal("0");
			//如果商品不存在  新增基础信息
			if(bgrBasicGoodsResult==null){
				bgpParam.setGoodsCustomerName(basicCustomer.getCustomerName());//客户名称
				bgpParam.setGoodsName(excelItem.getGoodsName());//商品名称
				bgpParam.setGoodsUnit(excelItem.getGoodsUnit());//单位 (基本单位)
				bgpParam.setGoodsBigtype(excelItem.getGoodsType());//商品大类 (品类描述)
				bgpParam.setGoodsWeight("0.1");//重量单位 默认1
				if (v.compareTo(as)==1) {//大于 返回1
					bgpParam.setGoodsVolume(v.toString());//体积
				} else {
					bgpParam.setGoodsVolume("0.1");//默认1
				}
				if(u.compareTo(as)==1) {//大于 返回1
					bgpParam.setGoodsCharging(u.toString());//计费指定价
				} else {
					bgpParam.setGoodsCharging("10");//默认1
				}
				bgpParam.setGoodsBottom("10");//底
				bgpParam.setGoodsLamination("10");//叠层
				bgpParam.setGoodsSupportvolume("10000");//每托存量 默认100
				bgpParam.setGoodsTraylayer("1");//托层 默认1
				bgpParam.setGoodsWarranty("36");
				bgpParam.setDeliverId(deliverId);
				bgpParam.setDeptId(deptId);
				bgpParam.setCreateTime(new Date());
				basicGoodsService.addReturnId(bgpParam);
				bgrBasicGoodsResult = new BasicGoodsResult();
				ToolUtil.copyProperties(bgpParam, bgrBasicGoodsResult);
			} else {
				boolean flag = false;//是否更新商品
				if (ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsVolume())) {
					BigDecimal volume =  new BigDecimal(bgrBasicGoodsResult.getGoodsVolume());
					if(v.compareTo(volume) != 0) {
						bgrBasicGoodsResult.setGoodsVolume(v.toString());
						flag = true;
					}
				} else {
					bgrBasicGoodsResult.setGoodsVolume(v.toString());
					flag = true;
				}
				if (ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsCharging())) {
					BigDecimal charging =  new BigDecimal(bgrBasicGoodsResult.getGoodsCharging());
					if(u.compareTo(charging) != 0) {
						bgrBasicGoodsResult.setGoodsCharging(u.toString());
						flag = true;
					}
				} else {
					bgrBasicGoodsResult.setGoodsCharging(u.toString());
					flag = true;
				}
				if (flag) {
					ToolUtil.copyProperties(bgrBasicGoodsResult, bgpParam);
					basicGoodsService.update(bgpParam);
				}
			}
			BigDecimal goodsWeight = new BigDecimal(bgrBasicGoodsResult.getGoodsWeight());//重量单位
			
			//创建订单明细
			ToolOrderPutDetailedParam opdpDetailedParam = new ToolOrderPutDetailedParam();
			opdpDetailedParam.setPutDetailedNumber(toolOrderPutResult.getPutNumber());//入库订单编号
			opdpDetailedParam.setDetailedGoodsname(bgrBasicGoodsResult.getGoodsName());//商品名称
			opdpDetailedParam.setDetailedGoodsnum(Long.parseLong(bgrBasicGoodsResult.getId().toString()));//商品id
			opdpDetailedParam.setGoodsNumber(bgrBasicGoodsResult.getGoodsNumber());//商品编号
			opdpDetailedParam.setDetailedPutnum(putnum.toString());//应入数量
			opdpDetailedParam.setDetailedPutweight(putnum.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入重量
			opdpDetailedParam.setGoodsWeight(goodsWeight.toString());//重量
			opdpDetailedParam.setDetailedPutvolume(putnum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入体积
			opdpDetailedParam.setGoodsVolume(v.toString());//体积
			opdpDetailedParam.setDetailedUnitprice(u.toString());//单价
			opdpDetailedParam.setDetailedMoney(putnum.multiply(u).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//金额
			opdpDetailedParam.setDetailedLargeclass(bgrBasicGoodsResult.getGoodsBigtype());//商品大类 (导入品类描述)
			if(ToolUtil.isNotEmpty(excelItem.getGoodsUnit())) {
				opdpDetailedParam.setGoodsUnit(excelItem.getGoodsUnit());
			} else {
				opdpDetailedParam.setGoodsUnit(bgrBasicGoodsResult.getGoodsUnit());
			}
			opdpDetailedParam.setGoodsSpecs(bgrBasicGoodsResult.getGoodsSpecs());
			opdpDetailedParam.setCreateTime(new Date());
			detailedList.add(opdpDetailedParam);
			opdpDetailedParam = new ToolOrderPutDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(orderPutList);
			toolOrderPutDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		return data;
	}


	@Resource
    private ToolOrderPutDetailedService toolOrderPutDetailedService;

	@Resource
    private DeptService deptService;
	
	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@Override
	public boolean saveBatchList(List<ToolOrderPutParam> list) {
		return this.baseMapper.saveBatchList(list);
	}

	@Override
	public ResponseData savePulljstputorder(ToolOrderPutParam toolOrderPutParam, List<OrderPutExcelItem> list) {
		ResponseData data = new ResponseData();
		if(toolOrderPutParam.getWarehouseId()==null||toolOrderPutParam.getPutCustomerId()==null) {
			return ResponseData.error("请填写订单基本信息!");
		}
		List<ToolOrderPutParam> orderPutList = new ArrayList<ToolOrderPutParam>();//批量保存的 入库订单list
		List<ToolOrderPutDetailedParam> detailedList = new ArrayList<ToolOrderPutDetailedParam>();//批量保存的 订单商品明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(toolOrderPutParam.getPutCustomerId());//客户信息
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(toolOrderPutParam.getWarehouseId());//仓库信息
		//查询最新 入库订单
		ToolOrderPut toolOrderPut = this.findByThelastone();
    	int putNumber = 1;
    	if (toolOrderPut!=null) {
    		putNumber = toolOrderPut.getId()+1;
		} 
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
		String trayCode = getOperateIdOrderPrefix(user);
		for (OrderPutExcelItem excelItem : list) {
			if (ToolUtil.isEmpty(excelItem.getGoodsNumber())&&ToolUtil.isEmpty(excelItem.getGoodsName())) {
				break;
			} 
			if(ToolUtil.isEmpty(excelItem.getGoodsNumber())) {
				data.setSuccess(false);
				data.setMessage("导入数据中商品编号不得为空!");
				return data;
			}
			if(ToolUtil.isEmpty(excelItem.getPutnum())) {
				data.setSuccess(false);
				data.setMessage("导入数据中应入数量不得为空!");
				return data;
			}
			//通过 导入的客户单号 查询是否存在
			ToolOrderPutParam opp = new ToolOrderPutParam();
			boolean whether2 = false;
			if(ToolUtil.isEmpty(excelItem.getShipmentnumber())) {
				whether2 = true;
				excelItem.setShipmentnumber(trayCode+"-"+"YCRK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+(putNumber));
			}
			opp.setPutCustomerNumber(excelItem.getShipmentnumber());//客户单号 (客户货运订单号)
			ToolOrderPutResult toolOrderPutResult = this.findBySpec(opp,null);//状态不等于 作废
			//如果不存在
			if(toolOrderPutResult==null) {
				//新增入库订单
				opp.setPutNumber(trayCode+"-"+"YCRK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+(putNumber));
		    	opp.setPutCustomerId(toolOrderPutParam.getPutCustomerId());//客户id
		    	opp.setPutCustomerName(basicCustomer.getCustomerName());//客户名称
		    	opp.setWarehouseId(toolOrderPutParam.getWarehouseId());//仓库id
		    	opp.setWarehouseName(basicWarehouse.getWarehouseName());//仓库名称
		    	opp.setPutType("PICKUP_STORAGE");//入库类别 默认为‘提货入库’
	opp.setPutMode("WINDOW_RECEIVING");//入库方式 默认为‘窗口接货’  不生成货运订单
		    	opp.setSettlement(toolOrderPutParam.getSettlement());//结算方式
		    	opp.setCarnumber(excelItem.getCarNumber());//车牌号
		    	opp.setBillstate("PENDING_SUBMIT");//订单状态
		    	opp.setCreateName(user.getName());//制单人名称
		    	opp.setCreateTime(new Date());
		    	opp.setNotes(excelItem.getNotes());
		    	opp.setDeliverId(deliverId);//交付id
		    	opp.setDeptId(deptId);//部门id
		    	boolean whether = false;//判断客户单号  是否重复
		    	for (ToolOrderPutParam opp2 : orderPutList) {
					if (opp2.getPutCustomerNumber().equals(opp.getPutCustomerNumber())) {
						whether = true;
						toolOrderPutResult = new ToolOrderPutResult();
		    			ToolUtil.copyProperties(opp2,toolOrderPutResult);
					}
				}
		    	if (!whether) {
		    		orderPutList.add(opp);
		    		if(!whether2) {
		    			putNumber++;
		    		}
		    		toolOrderPutResult = new ToolOrderPutResult();
	    			ToolUtil.copyProperties(opp,toolOrderPutResult);
				}
    			opp = new ToolOrderPutParam();
			} else {
				continue;
			}
			
			//通过商品编号 查询商品是否存在
			BasicGoodsParam bgpParam = new BasicGoodsParam();
			bgpParam.setGoodsNumber(excelItem.getGoodsNumber());
			bgpParam.setGoodsCustomerId(Integer.parseInt(toolOrderPutParam.getPutCustomerId().toString()));
			BasicGoodsResult bgrBasicGoodsResult = basicGoodsService.findBySpec(bgpParam,null);
			//计算 单价，体积单位
			BigDecimal putnum = new BigDecimal(excelItem.getPutnum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);//应入数量
			BigDecimal putvolume =  new BigDecimal(0);//应入体积
			BigDecimal v = new BigDecimal(0);//体积单位
			BigDecimal u = new BigDecimal(0);//单价
			if (ToolUtil.isNotEmpty(excelItem.getPutvolume())) {
				putvolume =  new BigDecimal(excelItem.getPutvolume()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				v = putvolume.divide(putnum,8,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
			} else {
				if (bgrBasicGoodsResult != null && ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsVolume())) {
					v = new BigDecimal(bgrBasicGoodsResult.getGoodsVolume()).setScale(8, BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
					putvolume =  putnum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				} else {
					v =  new BigDecimal("0.1");
				}
			}
			BigDecimal detailedMoney = new BigDecimal(0);//金额
			if (ToolUtil.isNotEmpty(excelItem.getDetailedMoney())) {
				detailedMoney = new BigDecimal(excelItem.getDetailedMoney()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				u = detailedMoney.divide(putnum,3,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留3位)
			} else {
				if (bgrBasicGoodsResult != null && ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsCharging())) {
					u = new BigDecimal(bgrBasicGoodsResult.getGoodsCharging()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					detailedMoney = putnum.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				} else {
					u = new BigDecimal("10");
				}
			}
//			如果商品不存在  或者商品码号不一致  新增基础信息
			if(bgrBasicGoodsResult==null ||ToolUtil.isEmpty(bgrBasicGoodsResult.getGoodsNo())){
				try {
					//聚水潭商品编码获取国标码
					String  goodsInfo = justGoodsInfoApi.getSellerItem(basicCustomer.getJustAppkey(),
							basicCustomer.getJustAppsecret(),
							basicCustomer.getAccessToken(),
							excelItem.getGoodsNumber()+",",
							"1"
					);
					org.json.JSONObject jsonObject = new org.json.JSONObject(goodsInfo);
					if(jsonObject.get("code").toString().equals("0")) {
						String data1 = jsonObject.get("data").toString();
						JSONObject jsonObject1 = new JSONObject(data1);
						if (Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {

							Object datas = new JSONObject(data).get("datas");
							JSONArray jsonArray = new JSONArray(datas);
							String s = jsonArray.get(0).toString();
							JSONObject jsonObject2 = new JSONObject(s);
							String sku_code = jsonObject2.get("sku_code").toString();
							bgpParam.setGoodsNo(sku_code);
						}
					}

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			BigDecimal as = new BigDecimal("0");
			//如果商品不存在  新增基础信息
			if(bgrBasicGoodsResult==null){

				bgpParam.setGoodsCustomerName(basicCustomer.getCustomerName());//客户名称
				bgpParam.setGoodsName(excelItem.getGoodsName());//商品名称
				bgpParam.setGoodsUnit(excelItem.getGoodsUnit());//单位 (基本单位)
				bgpParam.setGoodsBigtype(excelItem.getGoodsType());//商品大类 (品类描述)
				bgpParam.setGoodsWeight("0.1");//重量单位 默认1
				if (v.compareTo(as)==1) {//大于 返回1
					bgpParam.setGoodsVolume(v.toString());//体积
				} else {
					bgpParam.setGoodsVolume("0.1");//默认1
				}
				if(u.compareTo(as)==1) {//大于 返回1
					bgpParam.setGoodsCharging(u.toString());//计费指定价
				} else {
					bgpParam.setGoodsCharging("10");//默认1
				}
				bgpParam.setGoodsBottom("10");//底
				bgpParam.setGoodsLamination("10");//叠层
				bgpParam.setGoodsSupportvolume("10000");//每托存量 默认100
				bgpParam.setGoodsTraylayer("1");//托层 默认1
				bgpParam.setGoodsWarranty("36");
				bgpParam.setDeliverId(deliverId);
				bgpParam.setDeptId(deptId);
				bgpParam.setCreateTime(new Date());
				basicGoodsService.addReturnId(bgpParam);
				bgrBasicGoodsResult = new BasicGoodsResult();
				ToolUtil.copyProperties(bgpParam, bgrBasicGoodsResult);
			} else {
				boolean flag = false;//是否更新商品
				if (ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsVolume())) {
					BigDecimal volume =  new BigDecimal(bgrBasicGoodsResult.getGoodsVolume());
					if(v.compareTo(volume) != 0) {
						bgrBasicGoodsResult.setGoodsVolume(v.toString());
						flag = true;
					}
				} else {
					bgrBasicGoodsResult.setGoodsVolume(v.toString());
					flag = true;
				}
				if (ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsCharging())) {
					BigDecimal charging =  new BigDecimal(bgrBasicGoodsResult.getGoodsCharging());
					if(u.compareTo(charging) != 0) {
						bgrBasicGoodsResult.setGoodsCharging(u.toString());
						flag = true;
					}
				} else {
					bgrBasicGoodsResult.setGoodsCharging(u.toString());
					flag = true;
				}
				if (flag) {
					ToolUtil.copyProperties(bgrBasicGoodsResult, bgpParam);
					basicGoodsService.update(bgpParam);
				}
			}
			BigDecimal goodsWeight = new BigDecimal(bgrBasicGoodsResult.getGoodsWeight());//重量单位
			
			//创建订单明细
			ToolOrderPutDetailedParam opdpDetailedParam = new ToolOrderPutDetailedParam();
			opdpDetailedParam.setPutDetailedNumber(toolOrderPutResult.getPutNumber());//入库订单编号
			opdpDetailedParam.setDetailedGoodsname(bgrBasicGoodsResult.getGoodsName());//商品名称
			opdpDetailedParam.setDetailedGoodsnum(Long.parseLong(bgrBasicGoodsResult.getId().toString()));//商品id
			opdpDetailedParam.setGoodsNumber(bgrBasicGoodsResult.getGoodsNumber());//商品编号
			opdpDetailedParam.setDetailedPutnum(putnum.toString());//应入数量
			opdpDetailedParam.setDetailedPutweight(putnum.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入重量
			opdpDetailedParam.setGoodsWeight(goodsWeight.toString());//重量
			opdpDetailedParam.setDetailedPutvolume(putnum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入体积
			opdpDetailedParam.setGoodsVolume(v.toString());//体积
			opdpDetailedParam.setDetailedUnitprice(u.toString());//单价
			opdpDetailedParam.setDetailedMoney(putnum.multiply(u).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//金额
			opdpDetailedParam.setDetailedLargeclass(bgrBasicGoodsResult.getGoodsBigtype());//商品大类 (导入品类描述)
			if(ToolUtil.isNotEmpty(excelItem.getGoodsUnit())) {
				opdpDetailedParam.setGoodsUnit(excelItem.getGoodsUnit());
			} else {
				opdpDetailedParam.setGoodsUnit(bgrBasicGoodsResult.getGoodsUnit());
			}
			opdpDetailedParam.setGoodsSpecs(bgrBasicGoodsResult.getGoodsSpecs());
			opdpDetailedParam.setCreateTime(new Date());
			detailedList.add(opdpDetailedParam);
			opdpDetailedParam = new ToolOrderPutDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(orderPutList);
			toolOrderPutDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		return data;
	}

	@Override
	public ResponseData savePulljstreturngoods(ToolOrderPutParam toolOrderPutParam, List<OrderPutExcelItem> list) {
		ResponseData data = new ResponseData();
		if(toolOrderPutParam.getWarehouseId()==null||toolOrderPutParam.getPutCustomerId()==null) {
			return ResponseData.error("请填写订单基本信息!");
		}
		List<ToolOrderPutParam> orderPutList = new ArrayList<ToolOrderPutParam>();//批量保存的 入库订单list
		List<ToolOrderPutDetailedParam> detailedList = new ArrayList<ToolOrderPutDetailedParam>();//批量保存的 订单商品明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(toolOrderPutParam.getPutCustomerId());//客户信息
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(toolOrderPutParam.getWarehouseId());//仓库信息
		//查询最新 入库订单
		ToolOrderPut toolOrderPut = this.findByThelastone();
    	int putNumber = 1;
    	if (toolOrderPut!=null) {
    		putNumber = toolOrderPut.getId()+1;
		} 
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
		String trayCode = getOperateIdOrderPrefix(user);
		for (OrderPutExcelItem excelItem : list) {
			if (ToolUtil.isEmpty(excelItem.getGoodsNumber())&&ToolUtil.isEmpty(excelItem.getGoodsName())) {
				break;
			} 
			if(ToolUtil.isEmpty(excelItem.getGoodsNumber())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中商品编号不得为空!");
				return data;
			}
			if(ToolUtil.isEmpty(excelItem.getPutnum())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中应入数量不得为空!");
				return data;
			}
			//通过 导入的客户单号 查询是否存在
			ToolOrderPutParam opp = new ToolOrderPutParam();
			boolean whether2 = false;
			if(ToolUtil.isEmpty(excelItem.getShipmentnumber())) {
				whether2 = true;
				excelItem.setShipmentnumber(trayCode+"-"+"YCRK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+(putNumber));
			}
			opp.setPutCustomerNumber(excelItem.getShipmentnumber());//客户单号 (客户货运订单号)
			ToolOrderPutResult toolOrderPutResult = this.findBySpec(opp,null);//状态不等于 作废
			//如果不存在
			if(toolOrderPutResult==null) {
				//新增入库订单
				opp.setPutNumber(trayCode+"-"+"YCRK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+(putNumber));
		    	opp.setPutCustomerId(toolOrderPutParam.getPutCustomerId());//客户id
		    	opp.setPutCustomerName(basicCustomer.getCustomerName());//客户名称
		    	opp.setWarehouseId(toolOrderPutParam.getWarehouseId());//仓库id
		    	opp.setWarehouseName(basicWarehouse.getWarehouseName());//仓库名称
		    	opp.setPutType("RETURN_STORAGE");//入库类别 默认为‘提货入库’
	opp.setPutMode("WINDOW_RECEIVING");//入库方式 默认为‘窗口接货’  不生成货运订单
		    	opp.setSettlement(toolOrderPutParam.getSettlement());//结算方式
		    	opp.setCarnumber(excelItem.getCarNumber());//车牌号
		    	opp.setBillstate("待提交");//订单状态
		    	opp.setCreateName(user.getName());//制单人名称
		    	opp.setCreateTime(new Date());
		    	opp.setNotes(excelItem.getNotes());
		    	opp.setDeliverId(deliverId);//交付id
		    	opp.setDeptId(deptId);//部门id
		    	boolean whether = false;//判断客户单号  是否重复
		    	for (ToolOrderPutParam opp2 : orderPutList) {
					if (opp2.getPutCustomerNumber().equals(opp.getPutCustomerNumber())) {
						whether = true;
						toolOrderPutResult = new ToolOrderPutResult();
		    			ToolUtil.copyProperties(opp2,toolOrderPutResult);
					}
				}
		    	if (!whether) {
		    		orderPutList.add(opp);
		    		if(!whether2) {
		    			putNumber++;
		    		}
		    		toolOrderPutResult = new ToolOrderPutResult();
	    			ToolUtil.copyProperties(opp,toolOrderPutResult);
				}
    			opp = new ToolOrderPutParam();
			} else {
				//如果 导入的客户单号 已存在
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中客户单号:"+excelItem.getShipmentnumber()+"已存在!");
				return data;
			}
			
			//通过商品编号 查询商品是否存在
			BasicGoodsParam bgpParam = new BasicGoodsParam();
			bgpParam.setGoodsNumber(excelItem.getGoodsNumber());
			bgpParam.setGoodsCustomerId(Integer.parseInt(toolOrderPutParam.getPutCustomerId().toString()));
			BasicGoodsResult bgrBasicGoodsResult = basicGoodsService.findBySpec(bgpParam,null);
			//计算 单价，体积单位
			BigDecimal putnum = new BigDecimal(excelItem.getPutnum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);//应入数量
			BigDecimal putvolume =  new BigDecimal(0);//应入体积
			BigDecimal v = new BigDecimal(0);//体积单位
			BigDecimal u = new BigDecimal(0);//单价
			if (ToolUtil.isNotEmpty(excelItem.getPutvolume())) {
				putvolume =  new BigDecimal(excelItem.getPutvolume()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				v = putvolume.divide(putnum,8,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
			} else {
				if (bgrBasicGoodsResult != null && ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsVolume())) {
					v = new BigDecimal(bgrBasicGoodsResult.getGoodsVolume()).setScale(8, BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
					putvolume =  putnum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				} else {
					v =  new BigDecimal("0.1");
				}
			}
			BigDecimal detailedMoney = new BigDecimal(0);//金额
			if (ToolUtil.isNotEmpty(excelItem.getDetailedMoney())) {
				detailedMoney = new BigDecimal(excelItem.getDetailedMoney()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				u = detailedMoney.divide(putnum,3,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留3位)
			} else {
				if (bgrBasicGoodsResult != null && ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsCharging())) {
					u = new BigDecimal(bgrBasicGoodsResult.getGoodsCharging()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					detailedMoney = putnum.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				} else {
					u = new BigDecimal("10");
				}
			}
			BigDecimal as = new BigDecimal("0");
			//如果商品不存在  新增基础信息
			if(bgrBasicGoodsResult==null){
				bgpParam.setGoodsCustomerName(basicCustomer.getCustomerName());//客户名称
				bgpParam.setGoodsName(excelItem.getGoodsName());//商品名称
				bgpParam.setGoodsUnit(excelItem.getGoodsUnit());//单位 (基本单位)
				bgpParam.setGoodsBigtype(excelItem.getGoodsType());//商品大类 (品类描述)
				bgpParam.setGoodsWeight("0.1");//重量单位 默认1
				if (v.compareTo(as)==1) {//大于 返回1
					bgpParam.setGoodsVolume(v.toString());//体积
				} else {
					bgpParam.setGoodsVolume("0.1");//默认1
				}
				if(u.compareTo(as)==1) {//大于 返回1
					bgpParam.setGoodsCharging(u.toString());//计费指定价
				} else {
					bgpParam.setGoodsCharging("10");//默认1
				}
				bgpParam.setGoodsBottom("10");//底
				bgpParam.setGoodsLamination("10");//叠层
				bgpParam.setGoodsSupportvolume("10000");//每托存量 默认100
				bgpParam.setGoodsTraylayer("1");//托层 默认1
				bgpParam.setGoodsWarranty("36");
				bgpParam.setDeliverId(deliverId);
				bgpParam.setDeptId(deptId);
				bgpParam.setCreateTime(new Date());
				basicGoodsService.addReturnId(bgpParam);
				bgrBasicGoodsResult = new BasicGoodsResult();
				ToolUtil.copyProperties(bgpParam, bgrBasicGoodsResult);
			} else {
				boolean flag = false;//是否更新商品
				if (ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsVolume())) {
					BigDecimal volume =  new BigDecimal(bgrBasicGoodsResult.getGoodsVolume());
					if(v.compareTo(volume) != 0) {
						bgrBasicGoodsResult.setGoodsVolume(v.toString());
						flag = true;
					}
				} else {
					bgrBasicGoodsResult.setGoodsVolume(v.toString());
					flag = true;
				}
				if (ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsCharging())) {
					BigDecimal charging =  new BigDecimal(bgrBasicGoodsResult.getGoodsCharging());
					if(u.compareTo(charging) != 0) {
						bgrBasicGoodsResult.setGoodsCharging(u.toString());
						flag = true;
					}
				} else {
					bgrBasicGoodsResult.setGoodsCharging(u.toString());
					flag = true;
				}
				if (flag) {
					ToolUtil.copyProperties(bgrBasicGoodsResult, bgpParam);
					basicGoodsService.update(bgpParam);
				}
			}
			BigDecimal goodsWeight = new BigDecimal(bgrBasicGoodsResult.getGoodsWeight());//重量单位
			
			//创建订单明细
			ToolOrderPutDetailedParam opdpDetailedParam = new ToolOrderPutDetailedParam();
			opdpDetailedParam.setPutDetailedNumber(toolOrderPutResult.getPutNumber());//入库订单编号
			opdpDetailedParam.setDetailedGoodsname(bgrBasicGoodsResult.getGoodsName());//商品名称
			opdpDetailedParam.setDetailedGoodsnum(Long.parseLong(bgrBasicGoodsResult.getId().toString()));//商品id
			opdpDetailedParam.setGoodsNumber(bgrBasicGoodsResult.getGoodsNumber());//商品编号
			opdpDetailedParam.setDetailedPutnum(putnum.toString());//应入数量
			opdpDetailedParam.setDetailedPutweight(putnum.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入重量
			opdpDetailedParam.setGoodsWeight(goodsWeight.toString());//重量
			opdpDetailedParam.setDetailedPutvolume(putnum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入体积
			opdpDetailedParam.setGoodsVolume(v.toString());//体积
			opdpDetailedParam.setDetailedUnitprice(u.toString());//单价
			opdpDetailedParam.setDetailedMoney(putnum.multiply(u).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//金额
			opdpDetailedParam.setDetailedLargeclass(bgrBasicGoodsResult.getGoodsBigtype());//商品大类 (导入品类描述)
			if(ToolUtil.isNotEmpty(excelItem.getGoodsUnit())) {
				opdpDetailedParam.setGoodsUnit(excelItem.getGoodsUnit());
			} else {
				opdpDetailedParam.setGoodsUnit(bgrBasicGoodsResult.getGoodsUnit());
			}
			opdpDetailedParam.setGoodsSpecs(bgrBasicGoodsResult.getGoodsSpecs());
			opdpDetailedParam.setCreateTime(new Date());
			detailedList.add(opdpDetailedParam);
			opdpDetailedParam = new ToolOrderPutDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(orderPutList);
			toolOrderPutDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		return data;
	}

	@Override
	public ResponseData savePulljstputorderNew(ToolOrderPutParam toolOrderPutParam, List<OrderPutExcelItem> list) {

			ResponseData data = new ResponseData();
			if(toolOrderPutParam.getWarehouseId()==null||toolOrderPutParam.getPutCustomerId()==null) {
				return ResponseData.error("请填写订单基本信息!");
			}
			List<ToolOrderPutParam> orderPutList = new ArrayList<ToolOrderPutParam>();//批量保存的 入库订单list
			List<ToolOrderPutDetailedParam> detailedList = new ArrayList<ToolOrderPutDetailedParam>();//批量保存的 订单商品明细list
			BasicCustomer basicCustomer = basicCustomerService.getById(toolOrderPutParam.getPutCustomerId());//客户信息
			BasicWarehouse basicWarehouse = basicWarehouseService.getById(toolOrderPutParam.getWarehouseId());//仓库信息
			//查询最新 入库订单
			ToolOrderPut toolOrderPut = this.findByThelastone();
			int putNumber = 1;
			if (toolOrderPut!=null) {
				putNumber = toolOrderPut.getId()+1;
			}
			User user = userService.getcurrentUser();
			Long deptId = user.getDeptId();
			Long deliverId = user.getDeliverId();
			String trayCode = getOperateIdOrderPrefix(user);
			for (OrderPutExcelItem excelItem : list) {
				if (ToolUtil.isEmpty(excelItem.getGoodsNumber())&&ToolUtil.isEmpty(excelItem.getGoodsName())) {
					break;
				}
				if(ToolUtil.isEmpty(excelItem.getGoodsNumber())) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					data.setSuccess(false);
					data.setMessage("导入数据中商品编号不得为空!");
					return data;
				}
				if(ToolUtil.isEmpty(excelItem.getPutnum())) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					data.setSuccess(false);
					data.setMessage("导入数据中应入数量不得为空!");
					return data;
				}
				//通过 导入的客户单号 查询是否存在
				ToolOrderPutParam opp = new ToolOrderPutParam();
				boolean whether2 = false;
				if(ToolUtil.isEmpty(excelItem.getShipmentnumber())) {
					whether2 = true;
					excelItem.setShipmentnumber(trayCode+"-"+"YCRK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+(putNumber));
				}
				opp.setPutCustomerNumber(excelItem.getShipmentnumber());//客户单号 (客户货运订单号)
				ToolOrderPutResult toolOrderPutResult = this.findBySpec(opp,null);//状态不等于 作废
				//如果不存在
				if(toolOrderPutResult==null) {
					//新增入库订单
					opp.setPutNumber(trayCode+"-"+"YCRK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+(putNumber));
					opp.setPutCustomerId(toolOrderPutParam.getPutCustomerId());//客户id
					opp.setPutCustomerName(basicCustomer.getCustomerName());//客户名称
					opp.setWarehouseId(toolOrderPutParam.getWarehouseId());//仓库id
					opp.setWarehouseName(basicWarehouse.getWarehouseName());//仓库名称
					opp.setPutType("RETURN_STORAGE");//入库类别 默认为‘提货入库’
	opp.setPutMode("WINDOW_RECEIVING");//入库方式 默认为‘窗口接货’  不生成货运订单
					opp.setSettlement(toolOrderPutParam.getSettlement());//结算方式
					opp.setCarnumber(excelItem.getCarNumber());//车牌号
					opp.setBillstate("待提交");//订单状态
					opp.setCreateName(user.getName());//制单人名称
					opp.setCreateTime(new Date());
					opp.setNotes(excelItem.getNotes());
					opp.setDeliverId(deliverId);//交付id
					opp.setDeptId(deptId);//部门id
					boolean whether = false;//判断客户单号  是否重复
					for (ToolOrderPutParam opp2 : orderPutList) {
						if (opp2.getPutCustomerNumber().equals(opp.getPutCustomerNumber())) {
							whether = true;
							toolOrderPutResult = new ToolOrderPutResult();
							ToolUtil.copyProperties(opp2,toolOrderPutResult);
						}
					}
					if (!whether) {
						orderPutList.add(opp);
						if(!whether2) {
							putNumber++;
						}
						toolOrderPutResult = new ToolOrderPutResult();
						ToolUtil.copyProperties(opp,toolOrderPutResult);
					}
					opp = new ToolOrderPutParam();
				} else {
					//如果 导入的客户单号 已存在
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					data.setSuccess(false);
					data.setMessage("导入数据中客户单号:"+excelItem.getShipmentnumber()+"已存在!");
					return data;
				}

				//通过商品编号 查询商品是否存在
				BasicGoodsParam bgpParam = new BasicGoodsParam();
				bgpParam.setGoodsNumber(excelItem.getGoodsNumber());
				bgpParam.setGoodsCustomerId(Integer.parseInt(toolOrderPutParam.getPutCustomerId().toString()));
				BasicGoodsResult bgrBasicGoodsResult = basicGoodsService.findBySpec(bgpParam,null);
				//计算 单价，体积单位
				BigDecimal putnum = new BigDecimal(excelItem.getPutnum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);//应入数量
				BigDecimal putvolume =  new BigDecimal(0);//应入体积
				BigDecimal v = new BigDecimal(0);//体积单位
				BigDecimal u = new BigDecimal(0);//单价
				if (ToolUtil.isNotEmpty(excelItem.getPutvolume())) {
					putvolume =  new BigDecimal(excelItem.getPutvolume()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					v = putvolume.divide(putnum,8,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
				} else {
					if (bgrBasicGoodsResult != null && ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsVolume())) {
						v = new BigDecimal(bgrBasicGoodsResult.getGoodsVolume()).setScale(8, BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
						putvolume =  putnum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					} else {
						v =  new BigDecimal("0.1");
					}
				}
				BigDecimal detailedMoney = new BigDecimal(0);//金额
				if (ToolUtil.isNotEmpty(excelItem.getDetailedMoney())) {
					detailedMoney = new BigDecimal(excelItem.getDetailedMoney()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					u = detailedMoney.divide(putnum,3,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留3位)
				} else {
					if (bgrBasicGoodsResult != null && ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsCharging())) {
						u = new BigDecimal(bgrBasicGoodsResult.getGoodsCharging()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
						detailedMoney = putnum.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					} else {
						u = new BigDecimal("10");
					}
				}
				BigDecimal as = new BigDecimal("0");
				//如果商品不存在  新增基础信息
				if(bgrBasicGoodsResult==null){
					bgpParam.setGoodsCustomerName(basicCustomer.getCustomerName());//客户名称
					bgpParam.setGoodsName(excelItem.getGoodsName());//商品名称
					bgpParam.setGoodsUnit(excelItem.getGoodsUnit());//单位 (基本单位)
					bgpParam.setGoodsBigtype(excelItem.getGoodsType());//商品大类 (品类描述)
					bgpParam.setGoodsWeight("0.1");//重量单位 默认1
					if (v.compareTo(as)==1) {//大于 返回1
						bgpParam.setGoodsVolume(v.toString());//体积
					} else {
						bgpParam.setGoodsVolume("0.1");//默认1
					}
					if(u.compareTo(as)==1) {//大于 返回1
						bgpParam.setGoodsCharging(u.toString());//计费指定价
					} else {
						bgpParam.setGoodsCharging("10");//默认1
					}
					bgpParam.setGoodsBottom("10");//底
					bgpParam.setGoodsLamination("10");//叠层
					bgpParam.setGoodsSupportvolume("10000");//每托存量 默认100
					bgpParam.setGoodsTraylayer("1");//托层 默认1
					bgpParam.setGoodsWarranty("36");
					bgpParam.setDeliverId(deliverId);
					bgpParam.setDeptId(deptId);
					bgpParam.setCreateTime(new Date());
					basicGoodsService.addReturnId(bgpParam);
					bgrBasicGoodsResult = new BasicGoodsResult();
					ToolUtil.copyProperties(bgpParam, bgrBasicGoodsResult);
				} else {
					boolean flag = false;//是否更新商品
					if (ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsVolume())) {
						BigDecimal volume =  new BigDecimal(bgrBasicGoodsResult.getGoodsVolume());
						if(v.compareTo(volume) != 0) {
							bgrBasicGoodsResult.setGoodsVolume(v.toString());
							flag = true;
						}
					} else {
						bgrBasicGoodsResult.setGoodsVolume(v.toString());
						flag = true;
					}
					if (ToolUtil.isNotEmpty(bgrBasicGoodsResult.getGoodsCharging())) {
						BigDecimal charging =  new BigDecimal(bgrBasicGoodsResult.getGoodsCharging());
						if(u.compareTo(charging) != 0) {
							bgrBasicGoodsResult.setGoodsCharging(u.toString());
							flag = true;
						}
					} else {
						bgrBasicGoodsResult.setGoodsCharging(u.toString());
						flag = true;
					}
					if (flag) {
						ToolUtil.copyProperties(bgrBasicGoodsResult, bgpParam);
						basicGoodsService.update(bgpParam);
					}
				}
				BigDecimal goodsWeight = new BigDecimal(bgrBasicGoodsResult.getGoodsWeight());//重量单位

				//创建订单明细
				ToolOrderPutDetailedParam opdpDetailedParam = new ToolOrderPutDetailedParam();
				opdpDetailedParam.setPutDetailedNumber(toolOrderPutResult.getPutNumber());//入库订单编号
				opdpDetailedParam.setDetailedGoodsname(bgrBasicGoodsResult.getGoodsName());//商品名称
				opdpDetailedParam.setDetailedGoodsnum(Long.parseLong(bgrBasicGoodsResult.getId().toString()));//商品id
				opdpDetailedParam.setGoodsNumber(bgrBasicGoodsResult.getGoodsNumber());//商品编号
				opdpDetailedParam.setDetailedPutnum(putnum.toString());//应入数量
				opdpDetailedParam.setDetailedPutweight(putnum.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入重量
				opdpDetailedParam.setGoodsWeight(goodsWeight.toString());//重量
				opdpDetailedParam.setDetailedPutvolume(putnum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入体积
				opdpDetailedParam.setGoodsVolume(v.toString());//体积
				opdpDetailedParam.setDetailedUnitprice(u.toString());//单价
				opdpDetailedParam.setDetailedMoney(putnum.multiply(u).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());//金额
				opdpDetailedParam.setDetailedLargeclass(bgrBasicGoodsResult.getGoodsBigtype());//商品大类 (导入品类描述)
				if(ToolUtil.isNotEmpty(excelItem.getGoodsUnit())) {
					opdpDetailedParam.setGoodsUnit(excelItem.getGoodsUnit());
				} else {
					opdpDetailedParam.setGoodsUnit(bgrBasicGoodsResult.getGoodsUnit());
				}
				opdpDetailedParam.setGoodsSpecs(bgrBasicGoodsResult.getGoodsSpecs());
				opdpDetailedParam.setCreateTime(new Date());
				detailedList.add(opdpDetailedParam);
				opdpDetailedParam = new ToolOrderPutDetailedParam();
			}
			if(detailedList.size()>0){
				this.saveBatchList(orderPutList);
				toolOrderPutDetailedService.saveBatchList(detailedList);
			}
			data.setSuccess(true);
			return data;
	}


}
